package com.example.xd.fmpeg_test;

import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import android.widget.VideoView;

import com.example.xd.fmpeg_test.weight.LoadingDialog;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import VideoHandle.EpDraw;
import VideoHandle.EpEditor;
import VideoHandle.EpVideo;
import VideoHandle.OnEditorListener;

public class EditVideoActivity extends AppCompatActivity implements View.OnClickListener, MediaPlayer.OnPreparedListener {

    private EpVideo mEpVideo;
    public static final int FILTER_CODE = 1;
    private VideoView mVideo_view;
    private LoadingDialog mLoadingDialog;
    String type_back;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_video);
        mVideo_view = findViewById(R.id.video_view);
        mLoadingDialog = new LoadingDialog(this);
        findViewById(R.id.btn_add_lv).setOnClickListener(this);
        findViewById(R.id.btn_add_img).setOnClickListener(this);
        findViewById(R.id.btn_add_music).setOnClickListener(this);
        findViewById(R.id.btn_add_word).setOnClickListener(this);
        findViewById(R.id.btn_video2img).setOnClickListener(this);
        Intent intent = getIntent();
        String type = intent.getStringExtra("type");
        ArrayList<LocalMedia> content = intent.getParcelableArrayListExtra("content");
        Log.i("xd----", type);

        for (int i = 0; i < content.size(); i++) {
            Log.i("xd----", content.get(i).getPath());
        }
        if (type.equals("video")) {
            deitViewo(content);
        } else {
            deitImage(content);
        }
    }

    private void deitImage(ArrayList<LocalMedia> content) {
        String picPath = Environment.getExternalStorageDirectory() + "/" + getPackageName() + "/picpath/";
        File file = new File(picPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        String outfilePath = Environment.getExternalStorageDirectory() + "/" + getPackageName() + "/img_video/";
        File outfile = new File(outfilePath);
        if (!outfile.exists()) {
            outfile.mkdirs();
        }
        for (int i = 0; i < content.size(); i++) {
            String path = content.get(i).getPath();
            String newParh = picPath + "00" + i + ".jpg";
            if (copyFile(path, newParh)) {
                Log.i("xd---------", "拷贝图片成功" + i + "---" + newParh);
            }
        }
        EpEditor.pic2video(picPath + "%03d.jpg", outfilePath, 480, 320, 30, new OnEditorListener() {
            @Override
            public void onSuccess() {
                Log.i("xd-----", "图片合成视频成功");
            }

            @Override
            public void onFailure() {
                Log.i("xd-----", "图片合成视频失败");

            }

            @Override
            public void onProgress(float progress) {
                Log.i("xd-----", "图片合成视频" + progress);

            }
        });
    }

    private void deitViewo(ArrayList<LocalMedia> content) {
        String url = null;
        for (int i = 0; i < content.size(); i++) {
            url = content.get(i).getPath();
        }
        mEpVideo = new EpVideo(url);
        mVideo_view.setVideoPath(url);
        mVideo_view.setOnPreparedListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_add_lv:
                Intent intent = new Intent(this, FilterActivity.class);
                startActivityForResult(intent, FILTER_CODE);
                break;
            case R.id.btn_add_img:
                type_back = "image";
                PictureSelector.create(EditVideoActivity.this)
                        .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                        .maxSelectNum(1)// 最大图片选择数量 int
                        .minSelectNum(1)// 最小选择数量 int
                        .imageSpanCount(4)// 每行显示个数 int
                        .selectionMode(PictureConfig.SINGLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                        .previewImage(true)// 是否可预览图片 true or false
                        .isCamera(true)// 是否显示拍照按钮 true or false
                        .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                        .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                        .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                        .setOutputCameraPath("/CustomPath")// 自定义拍照保存路径,可不填
                        .enableCrop(false)// 是否裁剪 true or false
                        .compress(true)// 是否压缩 true or false
                        .glideOverride(800, 800)// int glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                        .withAspectRatio(1, 1)// int 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                        .hideBottomControls(false)// 是否显示uCrop工具栏，默认不显示 true or false
                        .isGif(true)// 是否显示gif图片 true or false
                        .freeStyleCropEnabled(true)// 裁剪框是否可拖拽 true or false
                        .circleDimmedLayer(true)// 是否圆形裁剪 true or false
                        .showCropFrame(true)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false   true or false
                        .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false    true or false
                        .openClickSound(false)// 是否开启点击声音 true or false
                        .previewEggs(true)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
                        .cropCompressQuality(90)// 裁剪压缩质量 默认90 int
                        .minimumCompressSize(100)// 小于100kb的图片不压缩
                        .synOrAsy(true)//同步true或异步false 压缩 默认同步
                        .cropWH(800, 800)// 裁剪宽高比，设置如果大于图片本身宽高则无效 int
                        .rotateEnabled(true) // 裁剪是否可旋转图片 true or false
                        .scaleEnabled(true)// 裁剪是否可放大缩小图片 true or false
                        .isDragFrame(false)// 是否可拖动裁剪框(固定)
                        .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
                break;
            case R.id.btn_add_music:
                type_back = "music";
                PictureSelector.create(EditVideoActivity.this)
                        .openGallery(PictureMimeType.ofAudio())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                        .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                        .openClickSound(false)// 是否开启点击声音 true or false
                        .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
                break;
            case R.id.btn_add_word:
                break;
            case R.id.btn_video2img:
                video2img(mEpVideo);

                break;
        }
    }

    private void video2img(EpVideo epVideo) {
        String outfilePath = Environment.getExternalStorageDirectory() + "/video2img/";
        File file = new File(outfilePath);
        if (file.exists()) {
            if (file.isFile()) {
                file.delete();
            } else {
                File[] files = file.listFiles();
                for (int i = 0; i < files.length; i++) {
                    file.delete();
                }
            }
        }
        if (!file.exists()) {
            file.mkdirs();
        }
        EpEditor.video2pic(epVideo.getVideoPath(), outfilePath, 480, 360, 2, new OnEditorListener() {
            @Override
            public void onSuccess() {
                Log.i("xd----", "video2pic----success");
            }

            @Override
            public void onFailure() {
                Log.i("xd----", "video2pic----failure");

            }

            @Override
            public void onProgress(float progress) {
                Log.i("xd----", "video2pic----" + progress);

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Bundle bundle = data.getExtras();
        switch (resultCode) {
            case RESULT_OK:
                switch (requestCode) {
                    case FILTER_CODE:
                        String filter_path = bundle.getString("filter_path");
                        addFilter(filter_path);
                        break;
                    case PictureConfig.CHOOSE_REQUEST:
                        List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                        LocalMedia localMedia = selectList.get(0);
                        if (type_back == "image") {
                            addImage(localMedia);
                        } else if (type_back == "music") {
                            addMusic(localMedia);
                        }
                        break;
                }
                break;
        }
    }

    private void addMusic(LocalMedia localMedia) {
        final String path = localMedia.getPath();
        Log.i("xd-----", path);
        final String outfilePath = Environment.getExternalStorageDirectory() + "/" + getPackageName() + "/music/";
        File file = new File(outfilePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        EpEditor.music(mEpVideo.getVideoPath(), path, outfilePath + "music.mp4", 0.0f, 1.0f, new OnEditorListener() {
            @Override
            public void onSuccess() {
                Log.i("xd-------", "添加音乐成功");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mVideo_view.setVideoPath(outfilePath + "music.mp4");
                        mVideo_view.start();
                    }
                });
            }

            @Override
            public void onFailure() {
                Log.i("xd-------", "添加音乐失败");
            }

            @Override
            public void onProgress(float progress) {
                //这里获取处理进度
                Log.i("xd-------", "添加音乐" + progress);

            }
        });
    }

    private void addImage(LocalMedia localMedia) {
        String path = localMedia.getPath();
        int width = localMedia.getWidth();
        int height = localMedia.getHeight();
        EpDraw epDraw;
        if (path.endsWith(".gif")) {
            epDraw = new EpDraw(path, 10, 10, width, height, true);
        } else {
            epDraw = new EpDraw(path, 10, 10, width, height, false);
        }
        mEpVideo.addDraw(epDraw);
        final String outpath = Environment.getExternalStorageDirectory() + "/" + getPackageName() + "/image/";
        File file = new File(outpath);
        if (!file.exists()) {
            file.mkdirs();
        }
        EpEditor.OutputOption outputOption = new EpEditor.OutputOption(outpath + "addimage.mp4");
        outputOption.setWidth(480);
        outputOption.setHeight(360);
        outputOption.frameRate = 30;
        outputOption.bitRate = 10;
        EpEditor.exec(mEpVideo, outputOption, new OnEditorListener() {
            @Override
            public void onSuccess() {
                Log.i("xd---------", "添加图片成功");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mVideo_view.setVideoPath(outpath + "addimage.mp4");
                        mVideo_view.start();
                    }
                });
            }

            @Override
            public void onFailure() {
                Log.i("xd---------", "添加图片失败");

            }

            @Override
            public void onProgress(float v) {
                Log.i("xd---------", "添加图片" + v);

            }
        });
    }

    private void addFilter(String filter_path) {
        mEpVideo.addFilter(filter_path);

        String outpath = Environment.getExternalStorageDirectory() + "/" + getPackageName() + "/filter/";
        File file = new File(outpath);
        if (!file.exists()) {
            file.mkdirs();
        }
        outpath = outpath + "output.mp4";
        Log.i("xd---------", outpath);
        EpEditor.OutputOption outputOption = new EpEditor.OutputOption(outpath);
        outputOption.setWidth(480);
        outputOption.setHeight(360);
        outputOption.frameRate = 30;
        outputOption.bitRate = 10;
        final String finalOutpath = outpath;
        EpEditor.exec(mEpVideo, outputOption, new OnEditorListener() {
            @Override
            public void onSuccess() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mVideo_view.setVideoPath(finalOutpath);
                        mVideo_view.start();
                    }
                });
                Log.i("xd---------", "添加滤镜成功");
//                mLoadingDialog.dismiss();
            }

            @Override
            public void onFailure() {
                Log.i("xd---------", "添加滤镜失败");
//                mLoadingDialog.setText("添加滤镜失败");
//                mLoadingDialog.dismiss();
            }

            @Override
            public void onProgress(final float v) {
//                mLoadingDialog.setText("" + v + "%");
                Log.i("xd---------", "添加滤镜" + v);

            }
        });


    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        mp.start();
    }

    public static boolean copyFile(String srcPath, String destDir) {
        boolean flag = false;
        File srcFile = new File(srcPath);
        if (!srcFile.exists()) { // 源文件不存在
            System.out.println("源文件不存在");
            return false;
        }

        if (destDir.equals(srcPath)) { // 源文件路径和目标文件路径重复
            System.out.println("源文件路径和目标文件路径重复!");
            return false;
        }
        File destFile = new File(destDir);
        if (destFile.exists() && destFile.isFile()) { // 该路径下已经有一个同名文件
            System.out.println("目标目录下已有同名文件!");
            return false;
        }
        String[] split = destDir.split(".");
        File file = new File(split[0]);
        if (!file.exists()) {
            file.mkdirs();
        }
        try {
            FileInputStream fis = new FileInputStream(srcPath);
            FileOutputStream fos = new FileOutputStream(destFile);
            byte[] buf = new byte[1024];
            int c;
            while ((c = fis.read(buf)) != -1) {
                fos.write(buf, 0, c);
            }
            fis.close();
            fos.close();

            flag = true;
        } catch (IOException e) {
        }

        if (flag) {
            System.out.println("复制文件成功!");
        }

        return flag;
    }

}
